package com.per.mybootall.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigInteger;

/**
 * Created with IntelliJ IDEA.
 *
 * @author: yyy
 * Date: 2021/10/19
 * Time: 9:13
 * Description:
 */
@Slf4j
public class AesUtils {
    //"算法/模式/补码方式"
    private static final String ALGORITHM = "AES/ECB/PKCS5Padding";

    //前后端统一密钥   16 32
    final static String key = "aKANZ9x6NQMu19zxaKANZ9x6NQMu19zx";

    public static String enCode(String content ) {
        if (key == null || "".equals(key)) {

            return null;
        }

        try {
            //获得密码的字节数组
            byte[] raw = key.getBytes();
            //根据密码生成AES密钥
            SecretKeySpec skey = new SecretKeySpec(raw, "AES");
            //根据指定算法ALGORITHM自成密码器
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            //初始化密码器，第一个参数为加密(ENCRYPT_MODE)或者解密(DECRYPT_MODE)操作，第二个参数为生成的AES密钥
            cipher.init(Cipher.ENCRYPT_MODE, skey);
            //获取加密内容的字节数组(设置为utf-8)不然内容中如果有中文和英文混合中文就会解密为乱码
            byte[] byte_content = content.getBytes("utf-8");
            //密码器加密数据
            byte[] encode_content = cipher.doFinal(byte_content);
            //将加密后的数据转换为字符串返回
            return Base64.encodeBase64String(encode_content);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /*
     * AES解密
     */

    public static String deCode(String content ) {
        if (key == null || "".equals(key)) {

            return null;
        }

        try {
            //获得密码的字节数组
            byte[] raw = key.getBytes();
            //根据密码生成AES密钥
            SecretKeySpec skey = new SecretKeySpec(raw, "AES");
            //根据指定算法ALGORITHM自成密码器
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            //初始化密码器，第一个参数为加密(ENCRYPT_MODE)或者解密(DECRYPT_MODE)操作，第二个参数为生成的AES密钥
            cipher.init(Cipher.DECRYPT_MODE, skey);
            //把密文字符串转回密文字节数组
            byte[] encode_content = Base64.decodeBase64(content);
            //密码器解密数据
            byte[] byte_content = cipher.doFinal(encode_content);
            //将解密后的数据转换为字符串返回
            return new String(byte_content, "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    public static void main(String[] args) {
        String content = "走iv先保存价值形成某种线擦速度";
        String enResult = enCode(content);
        System.out.println("--->" + enResult);
        String deResult = deCode(enResult);
        System.out.println("--->" + deResult);
    }
}
